import { loginByEmail, logout, getInfo } from 'api/login';
import { getToken, setToken, removeToken } from 'utils/auth';
import { getStudentCVstatus,fetchHrSettingStatus } from 'api/remoteSearch'
import axios from 'axios';



//权限有5种,学员,猎头,讲师,工作人员,管理员
//权限只设置到页面级别，没有到模块级别
//应该是已划分功能还赋予 角色享有功能
const permissionList = ['student', 'hr', 'teacher', 'staff', 'admin']
const user = {
  state: {
    user_id: '',
    status: '',
    router_added: false,
    code: '',
    token: getToken(),
    cvCompleted:false,
    completedCvCheck:false,//是否完成过简历检查
    name: '',
    avatar: '',
    hrSettingChecked:false,//是否设置过 猎头的详细信息
    introduction: '',
    roles: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    //
    SET_USER: (state, userId) => {
      state.user_id = userId;
    },
    SET_ROOTER_STATUS: (state, isRouterAdded) => {
      state.router_added = isRouterAdded;
    },
    SET_CV_STATUS:(state,isCompletedCv)=>{
      state.isCompletedCv=isCompletedCv;
    },
    SET_ROLES: (state, userType) => {
      state.roles.push(permissionList[userType])
      // state.roles = roles;
    },
    SET_HT_SETTING_STATUS:(state,isSetting)=>{
      state.hrSettingChecked=isSetting;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },

    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },

    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user_id = '';
    }
  },

  actions: {
    //检查猎头是否有设置详细信息
    checkHrSettingStatus({commit, state}){
      return new Promise((resolve,reject)=>{
        if(state.hrSettingChecked){//已经设置过了猎头信息
          resolve('ok')
        }
        fetchHrSettingStatus(state.user_id).then(res=>{
          if(res.data.status=='success'){
            resolve('ok')
            commit('SET_HT_SETTING_STATUS',true)
          }else{
            reject('no setting')
          }

        }).catch(err=>{
          reject("network error")
        })
      })
    },
    //检查是否需要提示student用户填写简历
    checkStudentInfoIsCollected({commit,state}){
      return new Promise((resolve,reject)=>{
        if(state.cvCompleted||state.roles.indexOf('student')==-1){
          //不是学员或者已经有填写过简历了
        }else{
          //学员
          getStudentCVstatus(state.user_id).then(response=>{
            let body=response.data;
            if(body.status=='success'){
              commit('SET_CV_STATUS',true)
            }else{
              //如果是学员给出填写简历的提示
              reject(new Error(body.msg))
            }
          }).catch(err=>{
            // reject(new Error("获取"))
          })
        }
      })
    },
    // 邮箱登录
    LoginByEmail({ commit }, userInfo) {
      const email = userInfo.email.trim();
      return new Promise((resolve, reject) => {
        loginByEmail(email, userInfo.password).then(response => {
          const data = response.data;
          if (data.status == 'success') {
            commit('SET_ROLES', data.data.type)
            commit('SET_NAME', data.data.name)
            commit('SET_USER', data.data.id)
            resolve(response);
          } else {
            resolve(response);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    //设置已经加载完所有路由了
    setRouterAdded({ commit }, isAdded) {
      return new Promise((resolve, reject) => {
        commit('SET_ROOTER_STATUS', isAdded)
        resolve("ok");
      }).catch(error => {
        reject(error)
      })
    },

    //设置扫描Qr获取到的用户信息
    setQrUserInfo({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        commit('SET_ROLES', userInfo.type)
        commit('SET_NAME', userInfo.name)
        commit('SET_USER', userInfo.id)
        resolve("ok");
      }).catch(error => {
        reject(error)
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // axios
        getInfo(state.token).then(response => {
          const data = response.data;
          commit('SET_ROLES', data.role);
          commit('SET_NAME', data.name);
          commit('SET_AVATAR', data.avatar);
          commit('SET_INTRODUCTION', data.introduction);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 第三方验证登录
    LoginByThirdparty({ commit, state }, code) {
      return new Promise((resolve, reject) => {
        commit('SET_CODE', code);
        loginByThirdparty(state.status, state.email, state.code).then(response => {
          commit('SET_TOKEN', response.data.token);
          setToken(response.data.token);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          commit('SET_ROOTER_STATUS', false)
          removeToken();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_ROOTER_STATUS', false)
        removeToken();
        resolve();
      });
    },

    // 动态修改权限
    ChangeRole({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_ROLES', [role]);
        commit('SET_TOKEN', role);
        setToken(role);
        resolve();
      })
    }
  }
};

export default user;
